package com.blog.common;

import com.blog.util.PropertiesUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
	
	//redis连接池
	private static JedisPool pool;  
	
	//最大连接数
	private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20")); 
	
	//在jedispool中最大的idle状态(空闲的)的jedis实例的个数
	private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10")); 
	
	//在jedispool中最小的idle状态(空闲的)的jedis实例的个数
	private static Integer minIdle = Integer.parseInt( PropertiesUtil.getProperty("redis.min.idle", "2")); 
	
	//在borrow一个jedis实例的时候,是否要进行验证操作,如果赋值true,则得到的jedis实例肯定是可以用的.
	private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true"));
	
	//在return一个jedis实例的时候,是否要进行验证操作,如果赋值true,则放回到 jedispool 的jedis实例肯定是可以用的.
	private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","false"));
	
	
	private static String redisIp = PropertiesUtil.getProperty("redis.ip");
	private static Integer redisPort = Integer.parseInt(PropertiesUtil.getProperty("redis.port"));
	
	
	private static void initPool(){
		
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		
		config.setTestOnBorrow(testOnBorrow);
		config.setTestOnReturn(testOnReturn);
		
		//连接耗尽的时候,是否阻塞,设置成false会抛出异常,true时会阻塞直到超时,默认为true.
		config.setBlockWhenExhausted(true);
		
		//第四个参数为超时时间
		pool = new JedisPool(config, redisIp,redisPort,1000*2);
	}
	
	//类一加载就初始化
	static{
		initPool();
	}
	
	//从连接池中得到一个jedis实例
	public static Jedis getJedis(){
		return pool.getResource();
	}
	
	//jedis 从3.0开始已经没有了 returnResource() 和 returnBrokenResource()方法
	public static void returnResource(Jedis jedis){
		
		//pool.returnResource(jedis);
	}
	
	public static void main(String[] args) {
		
		Jedis redis = pool.getResource();
		redis.set("abc", "youyoy");
		redis.close();

		System.out.println("啦啦啦");
	}
	
}
